import logging
import time
from colorama import Fore, Back, Style
import config

class CustomLogFormatter(logging.Formatter):
    printed_messages = set()

    def formatTime(self, record, datefmt=None):
        ct = self.converter(record.created)
        t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
        return f"{t},{int(record.msecs):03d}"

    def format(self, record):
        msg = super().format(record)
        original = record.getMessage()
        if "开始运行测试用例:" in original:
            if original in self.printed_messages:
                return ""
            self.printed_messages.add(original)
        return msg

class ColorStreamHandler(logging.StreamHandler):
    COLOR_MAP = {
        logging.DEBUG: Fore.CYAN,
        logging.INFO: Fore.WHITE,
        logging.WARNING: Fore.YELLOW,
        logging.ERROR: Fore.RED,
        logging.CRITICAL: Fore.RED + Back.WHITE,
        21: Fore.GREEN  # SUCCESS级别
    }

    def emit(self, record):
        try:
            msg = self.format(record)
            color = self.COLOR_MAP.get(record.levelno, Fore.WHITE)
            self.stream.write(f"{color}{msg}{Style.RESET_ALL}\n")
            self.flush()
        except Exception as e:
            print(f"日志输出异常: {str(e)}")

def setup_logging():
    log_file = config.REPORT_DIR / "test_run.log"
    formatter = CustomLogFormatter(fmt="%(asctime)s - %(levelname)-7s - %(message)s")
    file_handler = logging.FileHandler(log_file, encoding="utf-8")
    file_handler.setFormatter(formatter)
    console_handler = ColorStreamHandler()
    console_handler.setFormatter(formatter)

    root_logger = logging.getLogger()
    root_logger.setLevel(logging.INFO)
    root_logger.handlers = [file_handler, console_handler]

    # 屏蔽冗余日志
    logging.getLogger("airtest").setLevel(logging.INFO)
    logging.getLogger("airtest.report.report").setLevel(logging.WARNING)

    logging.addLevelName(21, "SUCCESS")
    logging.Logger.success = lambda inst, msg, *args, **kwargs: inst.log(21, msg, *args, **kwargs)